import 'package:get/get.dart';
import 'package:xiaofanshu_flutter/mapper/browse_history_mapper.dart';
import 'package:xiaofanshu_flutter/models/browse_history.dart';

class BrowseHistoryController extends GetxController {
  final BrowseHistoryMapper _historyMapper = BrowseHistoryMapper();
  
  final RxList<BrowseHistory> historyList = <BrowseHistory>[].obs;
  final RxBool isLoading = false.obs;

  @override
  void onInit() {
    super.onInit();
    loadHistory();
  }

  Future<void> loadHistory() async {
    isLoading.value = true;
    try {
      final history = await _historyMapper.getAllHistory();
      historyList.assignAll(history);
    } catch (e) {
      Get.log('加载浏览记录失败: $e');
    } finally {
      isLoading.value = false;
    }
  }

  Future<void> deleteHistory(int id) async {
    try {
      await _historyMapper.deleteHistory(id);
      historyList.removeWhere((item) => item.id == id);
      Get.snackbar('提示', '已删除浏览记录');
    } catch (e) {
      Get.log('删除浏览记录失败: $e');
      Get.snackbar('错误', '删除失败');
    }
  }

  Future<void> clearAllHistory() async {
    try {
      await _historyMapper.clearAllHistory();
      historyList.clear();
      Get.snackbar('提示', '已清空所有浏览记录');
    } catch (e) {
      Get.log('清空浏览记录失败: $e');
      Get.snackbar('错误', '清空失败');
    }
  }

  void navigateToNoteDetail(BrowseHistory history) {
    // 根据故事类型跳转到详情页
    try {
      int noteId = int.parse(history.noteId);
      history.type == 0 
          ? Get.toNamed('/notes/detail/image', arguments: noteId)
          : Get.toNamed('/notes/detail/video', arguments: noteId);
    } catch (e) {
      Get.log('转换故事ID失败: $e');
      Get.snackbar('错误', '故事ID格式错误');
    }
  }
}